/*Copyright by Catscratch
 *http://stackoverflow.com/questions/16353989/invalid-value-element-exi8-in-org-apache-xmlrpc
 */
package jTorrent;

import org.apache.ws.commons.util.NamespaceContextImpl;
import org.apache.xmlrpc.common.TypeFactoryImpl;
import org.apache.xmlrpc.common.XmlRpcController;
import org.apache.xmlrpc.common.XmlRpcStreamConfig;
import org.apache.xmlrpc.parser.AtomicParser;
import org.apache.xmlrpc.parser.TypeParser;
import org.apache.xmlrpc.serializer.TypeSerializer;
import org.apache.xmlrpc.serializer.TypeSerializerImpl;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

public class ModTypeFactory extends TypeFactoryImpl {
    public ModTypeFactory(XmlRpcController pController) {
        super(pController);
    }

    @Override
    public TypeParser getParser(XmlRpcStreamConfig pConfig, NamespaceContextImpl pContext, String pURI, String pLocalName) 
    {
        if (pLocalName.equals("i8")) 
        {
            return (TypeParser) new ModTypeParser();
        } else {
            return super.getParser(pConfig, pContext, pURI, pLocalName);
        }
    }

    public TypeSerializer getSerializer(XmlRpcStreamConfig pConfig, Object pObject) throws SAXException 
    {
    if (pObject instanceof Long) 
    {
        return new ModTypeSerializer();
    } else {
        return super.getSerializer(pConfig, pObject);
    }
}

private class ModTypeSerializer extends TypeSerializerImpl 
{
    /** Tag name of an i8 value.
     */
    public static final String I8_TAG = "i8";

    /** Fully qualified name of an i8 value.
     */
    public static final String EX_I8_TAG = "i8";

    @Override
    public void write(ContentHandler pHandler, Object pObject) throws SAXException {
            write(pHandler, I8_TAG, EX_I8_TAG, pObject.toString());
        }
    }

    private class ModTypeParser extends AtomicParser
    {
        protected void setResult(String pResult) throws SAXException {
            try {
                super.setResult(new Long(pResult.trim()));
            } catch (NumberFormatException e) {
                throw new SAXParseException("Failed to parse long value: " + pResult,
                                            getDocumentLocator());
            }
        }   

    }
}